package newfish.contacts.core.dao.impl;

import java.io.Serializable;
import java.util.List;


import newfish.contacts.core.dao.Dao;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
@SuppressWarnings("unchecked")
public class GenericDao<T> implements Dao<T> {
	
	protected Class<T> entityCls;
	protected SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory){
		this.sessionFactory = sessionFactory;
	}

	@Override
	public void delete(T entity) {
		Session session = sessionFactory.getCurrentSession();
		session.delete(entity);
	}

	@Override
	public List<T> listAll() {
		Session session = sessionFactory.getCurrentSession();
//		return session.createCriteria(entityCls).list();
//		Session session = sessionFactory.getCurrentSession();
//		Query query = session.createQuery("from Article a");
//		return session.createCriteria(clz).list();
//		return query.list();
		String hql = "from "+entityCls.getSimpleName()+" e";
		Query query = session.createQuery(hql);
		List<T> articles = query.list();
		return articles;
	}

	@Override
	public T findById(Serializable id) {
		Session session = sessionFactory.getCurrentSession();
		T entity = (T)session.get(entityCls, id);
		return entity;
	}

	@Override
	public List<T> findList(int pageNo, int pageSize) {
		Session session = sessionFactory.getCurrentSession();
		return session.createCriteria(entityCls).setFirstResult((pageNo-1)*pageSize).setMaxResults(pageSize).list();
	}

	@Override
	public Integer getCountOfAll() {
		Session session = sessionFactory.getCurrentSession();
		Integer count = (Integer)session.createCriteria(entityCls).setProjection(Projections.rowCount()).uniqueResult();
		return count != null ? count : 0;
	}

	@Override
	public void create(T entity) {
		Session session = sessionFactory.getCurrentSession();
		session.save(entity);
	}

	@Override
	public String update(T entity) {
		Session session = sessionFactory.getCurrentSession();
		session.update(entity);
		return "success";
	}

	@Override
	public void setEntityCls(Class<T> entityCls) {
		this.entityCls = entityCls;
	}

}
